<template>
	<view class="container">
		<view class="status_bar">
			<!-- 这里是状态栏 -->
		</view>
		<view class="header-bar">
			<!-- <view style="">{{ minTime }} ~~  {{ maxTime }} 总数：{{ this.list.length }}</view> -->
			<view>
				<switch
					:checked="isGroups ? true : false"
					style="transform: scale(0.85)"
					@change="switchChange"
				/>
			</view>
			<view class="search-bar">
				<uni-search-bar
					v-model="searchValue"
					
					@input="inputConfirm"
					cancelButton="none"
				>
				</uni-search-bar>
			</view>
		</view>

		<view class="list-box">
			<!-- <scroll-view :style="{height: `${windowHeight}px`}" scroll-y="true" > -->
			<uni-list class="content-list">
				<uni-list-item
					class="list-item"
					v-for="item in list"
					:key="item.date_time_int"
				>
					<template v-slot:body>
						<view>
							<view class="list-item-item">
								<text class="title pr5"
									>{{ item.name
									}}{{
										isGroups ? `(${item.user.replace("###", "")})` : ""
									}}</text
								>{{ item.current_time }} 情绪：{{ item.zdjs }}
							</view>
							<view class="list-item-item" :id="item.strategy_id+item.date_time_int">
								{{item.strategy_id}}{{item.date_time_int}}
								{{ item.zq }} {{ item.tip }} 价格：{{ item.close }}
								{{ item.industry_name }} {{ item.strategy_id }}
							</view>
						</view>
					</template>
				</uni-list-item>
			</uni-list>
			<!-- </scroll-view> -->
		</view>
		<view class="footer">
			<view class="footer-item" @click="showDrawer('showLeft')">队列</view>
			<view class="footer-item">{{ socketText }}</view>
			<view class="footer-item" @click="openPopup"
				>{{ myContactList.length > 0 ? myContactList[index].label : "" }}
				<uni-icons type="down" size="18"></uni-icons
			></view>
		</view>
		<uni-popup
			ref="popup"
			background-color="#fff"
			@change="popupChange"
			type="bottom"
		>
			<view class="popup-content">
				<view
					class="contact-item"
					:class="index == idx ? 'active' : ''"
					v-for="(item, idx) in myContactList"
					:key="item.name"
					@click="bindPickerChange(idx)"
					>{{ item.label }}
					<uni-icons
						v-if="index == idx"
						type="checkmarkempty"
						size="16"
						color="#2979ff"
					></uni-icons
				></view>
			</view>
		</uni-popup>
		<uni-drawer
			class="queueInfo"
			ref="showLeft"
			mode="left"
			@change="change($event, 'showLeft')"
		>
			<view class="queueInfo">
				<view class="queueInfo-item">
					<text>队列</text>
					<text>积压</text>
				</view>
				<view v-if="queueInfo && queueInfo.length > 0">
					<view class="queueInfo-item" v-for="item in queueInfo">
						<text>{{ item.q }}</text>
						<text>{{ item.count }}</text>
					</view>
				</view>
				<view v-else class="queueInfo-item">暂无数据</view>

				<view class="logout" @click="logout">
          <!-- <button type="default">退出登录</button> -->
          退出登录<uni-icons type="arrow-right" size="18" color="#2979ff"></uni-icons>
			</view>
			</view>
		</uni-drawer>
	</view>
</template>
<script>
// import { io } from "socket.io-client";
import io from "@hyoga/uni-socket.io";
const app = getApp({ allowDefault: true });
import { formatDate } from "../../utils/common";
export default {
	data() {
		return {
			userName: "",
			status: "more",
			searchValue: "",
			list: [],
			socketTask: null,
			myContactList: [],
			index: 0,
			queueInfo: [],
			minTime: "",
			maxTime: "",
			windowHeight: 100,
			triggered: false,
			loading: false,
			isGroups: false,
			socket: null,
			socketText: "",
			maxCount: 3000, //最大条数
			heartbeatInterval:null
		};
	},
	// 计算属性

	computed: {
		// 联系人名称
		contactName: function () {
			if (this.myContactList.length > 0 && this.index > -1) {
				return this.myContactList[this.index].name;
			} else {
				return "";
			}
		},
	},

	onShow() {},
	onReachBottom() {
		//console.log("到底啦");
		if (this.isGroups) {
			return;
		}
		this.scroll = 1;
		if (!this.loading) {
			this.getList();
		}
	},
	async onPullDownRefresh() {
		if (this.isGroups) {
			uni.stopPullDownRefresh();
			return;
		}
		this.scroll = -1;
		//console.log("上拉加载");
		if (!this.loading) {
			await this.getList();
		}

		uni.stopPullDownRefresh();
	},
	onReady() {
		const isGroups = uni.getStorageSync("isGroups");
		this.isGroups = isGroups;
		if (!this.userName) {
			const status = this.getUserName();
			if (!status) {
				return;
			}
		}
		if (!app.globalData.baseUrl) {
			const baseUrl = uni.getStorageSync("baseUrl");
			if (!baseUrl) {
				uni.redirectTo({
					url: "/pages/login/login",
				});
				return;
			}
			app.globalData.baseUrl = baseUrl;
		}
		if (this.myContactList.length == 0) {
			this.getMyContactList();
		}
		this.initParamData();
		this.getList();
		this.initSocket();
	},
	onUnload() {
		this.socket.disconnect();
	},
	onHide() {
		uni.setStorage({
			key: "isGroups",
			data: this.isGroups,
		});
	},

	methods: {
		initParamData() {
			this.list.splice(0);
			this.scroll = -1;
			this.maxTime = formatDate(new Date());
			this.minTime = this.maxTime;
		},
		getUserName() {
			const userName = app?.globalData.userName;
			if (!userName) {
				try {
					const value = uni.getStorageSync("userName");
					if (value) {
						//console.log("getStorageSync有数据");
						this.userName = value;
						return true;
					} else {
						//console.log("未登录，跳转登录页");
						uni.redirectTo({
							url: "/pages/login/login",
						});
						return false;
					}
				} catch (e) {
					// error
					return false;
				}
			} else {
				//console.log("globalData有数据");
				this.userName = userName;
				return true;
			}
		},
		change() {},
		// 打开窗口
		showDrawer(e) {
			this.$refs[e].open();
			this.getQueueInfo();
		},
		// 关闭窗口
		closeDrawer(e) {
			this.$refs[e].close();
		},
		getMyContactList() {
			try {
				const value = uni.getStorageSync("myContactList");
				if (value) {
					this.myContactList = JSON.parse(value);
				}
			} catch (e) {
				// error
			}
		},
		bindPickerChange(index) {
			this.index = index;
			this.$refs.popup.close();
			this.initParamData();
			this.getList();
		},
		initSocket() {
			this.socket = io(`${app.globalData.baseUrl}`, {
				transports: ["websocket"], // 强制使用 WebSocket
			});
			this.socket.on("connect", () => {
				console.log("Connected to the server");
				// 连接成功后，可以发送消息到服务器，例如发送用户名
				this.socket.emit("message", { username: this.contactName });
				this.heartbeatInterval = setInterval(() => {
						  // 发送自定义心跳事件到服务器
						  this.socket.emit('message', { username: this.contactName});
						}, 30000); // 30000毫秒，即30秒
			});
			this.socket.on("disconnect", () => {
				clearInterval(this.heartbeatInterval);
				console.log("disconnect");
			});
			this.socket.on("response", (data) => {
				//console.log("Received message:", data);
				if (!data.message.receivers) {
					return;
				}
				const name = data.message.data.split(" ")[0];

				let title = data.message.receivers + "    " + name;
				title = title.replace(/#/g, "");
				this.socketText = title;
				// #ifdef APP-PLUS

				const content = data.message.data.replace(name, "");
				//console.log("content", content);
				let options = {
					cover: false, //覆盖上次，只保留最后一个
					when: new Date(),
					title: title,
				};
				let body = {
					id: "id",
					key: "key",
				};
				let payload = JSON.stringify(body);
				plus.push.createMessage(content, payload, options);
				// #endif

				if (data.message.receivers.split(",").includes(this.contactName)) {
					this.scroll = 1;
					if (!this.loading) {
						this.getList();
					}
				}
			});
			this.socket.on("connect_error", (error) => {
				console.log("error", error);
			});
		},
		scrollToBottom() {
      uni.pageScrollTo({
        scrollTop: 999999, // 设置一个足够大的值确保滚动到底部
        duration: 300, // 滚动动画时长，单位ms
        //selector: `${this.list[this.list.length-1].strategy_id}${this.list[this.list.length-1].date_time_int}`,
        success:(e) => {
          console.log("pageScrollTo success", e);
        },
        fail: (e) => {
          console.log("pageScrollTo fail", e);
        },
      });
		   
		},
		async getList() {
			// console.log("app.globalData.baseUrl", app.globalData.baseUrl);
			this.loading = true;
			// uni.showLoading({
			// 	title: "加载中",
			// });
			const reqData = {
				// -1是上拉，查找历史，1下拉是查找最新
				checkPoint: this.scroll === -1 ? this.minTime : this.maxTime,
				scroll: this.scroll,
				pageSize: 10,
				keywords: this.searchValue,
				username: this.isGroups
					? this.myContactList.map((item) => item.name).toString()
					: this.contactName,
			};
			//console.log("reqData", reqData);
			uni.request({
				url: `${app.globalData.baseUrl}/api/scrollMsg`,
				method: "post",
				data: reqData,
				header: {
					"ngrok-skip-browser-warning": "true",
				},
				success: (data) => {
          let scrollBottom = false;
					if(this.list.length==0){
            scrollBottom = true;
          }
					const res = data.data.data;
          
					// console.log("getList请求成功", res);
					if (res.items?.length > 0) {
						if (this.isGroupVisible) {
							//分组结束
							this.list = res.items;
							return;
						}
						if (this.scroll == -1) {
							// const data = res.items.reverse();
							this.list.unshift(...res.items);
							if (this.list.length > this.maxCount) {
								this.list.splice(this.maxCount);
							}
						} else {
							this.list.push(...res.items);
							if (this.list.length > this.maxCount) {
								this.list.splice(this.maxCount - this.list.length);
							}
						}
						this.minTime = this.list[0].date_time_int;
						this.maxTime = this.list[this.list.length - 1].date_time_int;
					}
          this.$nextTick(()=>{
            if(this.scroll === 1 || scrollBottom){
              this.scrollToBottom()
            }
          })  
					this.loading = false;
					
					
				},
				fail: (e) => {
					this.loading = false;
					// console.log("getList请求fail", e);
				},
				complete: () => {
					// console.log("getList请求结束");
					// uni.hideLoading();
				},
			});
		},
		onAbort() {
			// console.log("onAbort");
		},
		async getQueueInfo(isClear = false) {
			// uni.showLoading({
			// 	title: "加载中",
			// });
			uni.request({
				url: `${app.globalData.baseUrl}/api/queueInfo`,
				success: (data) => {
					const res = data.data.data;
					// console.log(res, "res");
					this.queueInfo = res.items;
				},
				complete: () => {
					// uni.hideLoading();
				},
			});
		},
		switchChange(e) {
			this.isGroups = e.detail.value;
			this.initParamData();
			this.getList();
		},
		/** 搜索*/
		inputConfirm(e) {
			this.initParamData();
			this.searchValue = e;
			this.getList();
		},
		popupChange() {},
		openPopup() {
			this.$refs.popup.open();
		},
		logout() {
			this.socket.emit("logout", { data: "logout" });
			this.socket.disconnect();
			uni.redirectTo({
				url: "/pages/login/login",
			});
		},
	},
};
</script>
<style>
page {
	background-color: #ffffff;
}
.status_bar {
	height: var(--status-bar-height);
	width: 100%;
}
.container {
	padding-left: 0px;
	padding-right: 0px;
}

.header-bar {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;

	display: flex;
	padding: var(--status-bar-height) 20rpx 10rpx;
	box-sizing: border-box;
	align-items: center;
	z-index: 9;
	background-color: #fff;
	border-bottom: 1px solid #dedede;
}

.header-bar .name {
	font-size: 26rpx;
	padding-right: 20rpx;
}

.search-bar {
	flex: 1 1 auto;
}

.type-select {
	width: 80rpx;
	font-size: 24rpx;
	text-align: center;
}

.search-box {
	flex: 1 1 auto;
}

.fab-btn {
	display: flex;
	justify-content: center;
	align-items: center;
	position: fixed;
	right: 10rpx;
	bottom: 40rpx;
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background-color: rgb(0, 122, 255);
	box-shadow: 0 1px 5px 2px rgba(0, 0, 0, 0.3);
	color: #fff;
	font-size: 28rpx;
}

.queueInfo {
	position: relative;
	height: 100%;
	padding: calc(var(--status-bar-height) + 40rpx) 40rpx 100rpx;
	box-sizing: border-box;
}

.queueInfo .queueInfo-item {
	display: flex;
	justify-content: space-around;
	padding-bottom: 40rpx;
}

.content-list {
	/* padding: 20px 0; */
}

.list-item {
	padding: 0 10rpx;
	/* margin-bottom: 20rpx; */
	/* border-bottom: 1px solid #dedede; */
	color: #666;
}

.list-item-item {
	display: flex;
	/* padding-bottom: 10rpx; */
	flex-wrap: wrap;
}

.two-col {
	justify-content: space-between;
}
.pr5 {
	padding-right: 10rpx;
}
.title {
	color: #333;
}

.time {
	color: #999;
}
.footer {
	position: fixed;
	bottom: 0;
	width: 100%;
	height: 100rpx;
	display: flex;
	justify-content: space-between;
	background: #efefef;
}
.footer-item {
	width: 50%;
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: center;
}
.item-select {
	width: 50%;
	display: flex;
	height: 100%;
	align-items: center;
	justify-content: center;
	border-left: 1px solid #dedede;
	box-sizing: border-box;
}

.item-selec-left {
	padding-right: 20px;
	color: #999;
}

.select-box {
	display: flex;
	align-items: center;
	color: #333;
}

.select-box .uni-input {
	padding-right: 20rpx;
	font-size: 36rpx;
}
.list-box {
	padding: 60px 0 40px;
}

.popup-content {
	padding: 20px;
}

.contact-item {
	padding: 20rpx 0;
	text-align: center;
}
.active {
	color: #2979ff;
}
.logout {
	position: absolute;
	bottom: 30px;
  right: 10rpx;
  color: #2979ff;
}
</style>
